import {
  GetCaptcha,
  GetCaptchaVerify,
  GetUserLogin,
  GetHasRegist,
  GetUserRegist,
} from "apis/index";
import { regexp, showToast } from "utils/index";
const seconds = 59;
const app = getApp();
Page({
  data: {
    isAgree: true, //是否同意协议
    phone: "18483221518", //手机号
    password: "flc301415", //密码
    captcha: "8938", //验证码
    nickname: "别样的感动3014", //用户昵称
    disabled: false,
    countNum: seconds,
    isSendCaptcha: false, //是否发送了验证码
  },

  onLoad(options) {
    const { type = "captcha" } = options;
  },

  onShareAppMessage() {},
  toggleAgree(e) {
    this.setData({
      isAgree: e.detail,
    });
    this.updateDisabled();
  },
  //注册
  onRegist() {
    const { phone, password, nickname, captcha, isAgree } = this.data;
    GetHasRegist({ phone }).then((res) => {
      const { exist } = res;
      if (exist === 1) {
        showToast("该账号已注册");
      } else {
        GetUserRegist({
          phone,
          password,
          nickname,
          captcha,
        }).then((res) => {
          showToast("注册成功");
        });
      }
    });
  },
  //获取用户信息
  getUserInfo() {
    GetUserInfo({ uid: "" }).then((res) => {
      console.log("userInfo------------", res);
    });
  },
  onInput(e) {
    const { name } = e.currentTarget.dataset;
    const { value } = e.detail;
    this.setData({
      [name]: value,
    });
    // this.updateDisabled();
  },
  updateDisabled() {
    const { phone, captcha, isAgree } = this.data;
    this.setData({
      disabled: !(phone && captcha && isAgree),
    });
  },
  //检查电话号码
  checkPhone() {
    const { phone } = this.data;
    if (!phone) {
      showToast("请输入电话号码");
      return false;
    }
    if (!regexp.phone_11.test(phone)) {
      showToast("请输入正确的11位电话号码");
      return false;
    }
    return true;
  },
  //获取验证码
  getCaptcha() {
    const { phone, countNum, isSendCaptcha } = this.data;
    if (!this.checkPhone()) return;
    if (isSendCaptcha && !countNum < seconds) {
      showToast("已发送，请稍后再试");
      return;
    }
    this.setData({
      isSendCaptcha: true,
    });
    GetCaptcha({ phone }).then((res) => {
      const timer = setInterval(() => {
        const { countNum } = this.data;
        this.setData({
          countNum: countNum - 1,
        });
        if (countNum <= 1) {
          clearInterval(timer);
          this.setData({
            countNum: seconds,
            isSendCaptcha: false,
          });
        }
      }, 1000);
    });
  },
});
